<template>
    <div class="goods-detail-container">
      <!-- 骨架屏区域开始 -->
      <div class="crumbs-nav-wrap wrapper">
        <el-skeleton animated :loading="isShowSkeleton">
          <template #template>
            <el-skeleton-item style="width: 50px;margin: 0 10px;height: 25px;" />
            <el-skeleton-item style="width: 100px;margin: 0 10px;height: 25px;" />
            <el-skeleton-item style="width: 500px;margin: 0 10px;height: 25px;" />
          </template>
        </el-skeleton>
      </div>

      <el-skeleton class="wrapper" animated :loading="isShowSkeleton">
        <template #template>
          <div class="goods-wrap wrapper">
            <!-- 图片区域开始 -->
            <div class="image-wrap">
              <el-skeleton-item variant="image" style="width: 400px; height: 400px" />
              <div style="display: flex;justify-content: space-evenly;width: 400px;">
                <div style="display: flex;flex-direction: column;width: 100px;" v-for="(item, index) in 3" :key="index">
                  <el-skeleton-item variant="p" style="margin: 10px 0;" />
                  <el-skeleton-item variant="p" style="margin: 10px 0;" />
                  <el-skeleton-item variant="p" style="margin: 10px 0;" />
                </div>
              </div>
            </div>
            <div class="info-wrap">
              <div style="display: flex;flex-direction: column;">
                <el-skeleton-item variant="p" style="height: 30px;" />
                <el-skeleton-item variant="p" style="width: 140px;height: 20px;margin: 10px 0;" />
                <div style="margin-top: 20px;">
                  <el-skeleton-item variant="p" style="width: 10%;height: 30px;" />
                  <el-skeleton-item variant="p" style="width: 10%;height: 20px;margin-left: 6px;" />
                </div>
                <div style="margin-top: 30px;">
                  <div v-for="(item, index) in 3" :key="index">
                    <el-skeleton-item variant="p" style="width: 10%;margin: 10px 0;" />
                    <el-skeleton-item variant="p" style="width: 60%;margin: 10px 0 10px 20px;" />
                  </div>
                </div>

                <div style="display: flex;flex-direction: row;align-items: center; margin-top: 40px;">
                  <el-skeleton-item variant="p" style="width: 10%;height: 30px;" />
                  <div style="width: 400px;margin-left: 50px;">
                    <div style="display: flex;margin: 10px 0;" v-for="(item, index) in 4" :key="index">
                      <el-skeleton-item variant="p" style="width: 40%;height: 25px;" />
                      <el-skeleton-item variant="p" style="width: 40%;height: 25px;margin-left: 10px;" />
                    </div>
                  </div>
                </div>

                <div style="margin-top: 30px;">
                  <el-skeleton-item variant="p" style="width: 10%;height: 30px;" />
                  <el-skeleton-item variant="p" style="width: 25%;height: 30px;margin-left: 20px;" />
                </div>

                <div style="margin-top: 30px;">
                  <el-skeleton-item variant="p" style="width: 45%;height: 50px;border-top-left-radius: 25px;border-top-right-radius: 25px;border-bottom-right-radius: 25px;border-bottom-left-radius: 25px;" />
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-skeleton>
      <!-- 骨架屏区域结束 -->


      <!-- 面包屑导航区域开始 -->
      <div class="crumbs-nav-wrap wrapper" v-if="goods">
          <span>首页</span>
          <i class="iconfont icon-xiangyoujiantou"></i>
          <span>
              <a :href="`/goods-list?keyword=${goods.category_name}`">{{ goods.category_name }}</a>
          </span>
          <i class="iconfont icon-xiangyoujiantou"></i>
          <span>{{ goods.name }}</span>
      </div>
      <!-- 面包屑导航区域结束 -->

      <!-- 商品区域开始 -->
      <div class="goods-wrap wrapper" v-if="goods">
          <!-- 图片区域开始 -->
          <div class="image-wrap">
              <GoodsImage :images="goodsAlbums" :goodsSkuImg="goodsSkuImg" @setGoodsSkuImg="setGoodsSkuImg"/>
              <GoodsSales :goods="goods"/>
          </div>
          <!-- 图片区域结束 -->

          <!-- 信息区域开始 -->
          <div class="info-wrap" v-if="goods">
            <!-- 商品信息组件 -->
            <GoodsInfo :goods="goods"/>

            <!-- 规格选项组件 -->
            <GoodsSku :goodsOptions="goodsOptions" :goodsSkus="goodsSkus" @change="changeSku" :skuId="0"/>

            <!-- 数量选择组件 -->
            <TridentNumbox label="数量" v-model="num" :max="goods.amount"/>

            <div class="btn-wrap">
              <!-- 加入购物车 -->
              <div class="add-cart-btn" @click="handleAddCart">加入购物车</div>
              <div class="buy-btn" @click="hanleBuyNow">直接购买</div>
            </div>
          </div>
          <!-- 信息区域结束 -->

      </div>
      <!-- 商品区域结束 -->

      <!-- 商品推荐 -->
      <GoodsRecommend :cid="goods.cid" v-if="goods"/>

      <!-- 商品详情区域开始 -->
      <div class="goods-footer wrapper" v-if="goods">
        <div class="goods-article">
          <!-- 商品+评价 -->
          <GoodsTabs :goods="goods" />

          <!-- 注意事项 -->
          <GoodsWarn />
        </div>

        <!-- 24热榜+专题推荐 -->
        <div class="goods-aside">
          <GoodsHot :type="1" />
          <GoodsHot :type="11" />
          <GoodsHot :type="2" />
        </div>
      </div>

      <!-- 返回顶部组件 -->
      <TridentBackTop @backTop="backTop" :isShowBackTop="isShowBackTop"></TridentBackTop>
    </div>
</template>

<script setup>
import {reqGetGoodsDetailAPI} from '@/apis/goods'

import { onMounted, ref, watch, nextTick, provide } from 'vue'
import {useRoute, useRouter} from 'vue-router'
import { ElMessage, ElNotification } from 'element-plus'

// 引入组件
import GoodsImage from './components/GoodsImage.vue'
import GoodsSales from './components/GoodsSales.vue'
import GoodsInfo from './components/GoodsInfo.vue'
import GoodsSku from './components/GoodsSku.vue'
import GoodsRecommend from './components/GoodsRecommend.vue'
import GoodsTabs from './components/GoodsTabs.vue'
import GoodsWarn from './components/GoodsWarn.vue'
import GoodsHot from './components/GoodsHot.vue'

import { useCartStore } from "@/stores/modules/cart"
import { useOrderStore } from "@/stores/modules/order"
import useScroll from '@/utils/useScroll'


// ---------------- 定义全局变量开始 ----------------
// 购物车存储
const cartStore = useCartStore()

// 订单存储
const orderStore = useOrderStore()

// 商品信息
const goods = ref(null)

// 商品相册
const goodsAlbums = ref([])

// 商品属性
const goodsAttributes = ref([])

// 商品选项
const goodsOptions = ref([])

// 商品规格
const goodsSpecifications = ref([])

// 商品SKU
const goodsSkus = ref([])

// 商品SKU图片
const goodsSkuImg = ref('')

// 提供商品属性、相册数据
provide('goodsAttributes', goodsAttributes)
provide('goodsAlbums', goodsAlbums)

// 是否显示骨架
const isShowSkeleton = ref(false)

const router = useRouter()
// ---------------- 定义全局变量结束 ----------------

const setGoodsSkuImg = () => {
  goodsSkuImg.value = ''
}

// ---------------- 页面挂载完成开始 ----------------
onMounted(() => {
  getGoodsDetail()
})
// ---------------- 页面挂载完成结束 ----------------


// --------------------- 返回顶部功能开始 ---------------------
const isShowBackTop = ref(false)
const {scrollTop, scrollToTop} = useScroll()
watch(scrollTop, (oldValue, newValue) => {
    isShowBackTop.value = oldValue > 800 ? true : false
})

// 返回顶部
const backTop = () => {
    scrollToTop()
}
// --------------------- 返回顶部功能结束 ---------------------


// ---------------- 获取商品信息开始 ----------------
const getGoodsDetail = () => {
  // 路由
  const route = useRoute()
  // 解决路由商品ID发生变化时不会重新初始化组件的问题？？
  watch(() => route.query.id, async () => {
    if (route.query.id != undefined) {
      isShowSkeleton.value = true
      const result = await reqGetGoodsDetailAPI(route.query.id)
      if (result.code == 200) {
        goods.value = null
        goodsAlbums.value = []
        goodsAttributes.value = []
        goodsOptions.value = []
        goodsSpecifications.value = []
        goodsSkus.value = []
        nextTick(() => {
          goods.value = result.data.goods
          const albums = result.data.goods_albums != null ? result.data.goods_albums : []
          albums.forEach(item => {
            goodsAlbums.value.push(item.image_url)
          });

          // 商品属性
          goodsAttributes.value = result.data.goods_attributes != null ? result.data.goods_attributes : []

          // 商品规格选项
          let goodsOptionItems = result.data.goods_options != null ? result.data.goods_options : []
          goodsOptions.value = goodsOptionItems

          // 商品规格
          goodsSpecifications.value = result.data.goods_specifications != null ? result.data.goods_specifications : []

          // 商品SKU
          goodsSkus.value = result.data.goods_skus != null ? result.data.goods_skus : []

          // 设置标题
          document.title = `三叉戟商城-${goods.value.name}`
        })
      }
      isShowSkeleton.value = false
    }
  }, {immediate: true})
}
// ---------------- 获取商品信息结束 ----------------



// ---------------- 选择SKU功能开始 ----------------
// 定义商品数量
const num = ref(1)

// 定义选中的商品SKU
const currSku = ref(null)

// sku改变时候触发
const changeSku = (sku) => {
  if (sku.skuId) {
    goods.value.price = sku.price
    goods.value.amount = sku.inventory_num
    currSku.value = sku
    goodsSkuImg.value = sku.cover_url
  } else {
    currSku.value = null
  }
}
// ---------------- 选择SKU功能结束 ----------------



// --------------- 添加购物车功能开始 ---------------
const handleAddCart = async () => {
  if (!currSku.value) {
    ElMessage.error('请选择商品规格选项')
    return false
  }

  if (num.value > goods.value.amount) {
    ElMessage.error('库存不足')
    return false
  }

  if (cartStore.cartList.length > 50) {
    ElMessage.error('您购物车已满，请清理后再加入')
    return false
  }

  await cartStore.addCart({
    goods_id: goods.value.id,
    goods_sku_id: currSku.value.skuId,
    num: num.value,
    inventory_num: currSku.value.inventory_num,
    new_price: currSku.value.price,
    goods: {
      name: goods.value.name,
      cover_url: currSku.value.cover_url ? currSku.value.cover_url : goods.value.cover_url,
      price: currSku.value.price,
    },
    goods_sepc_option_text: currSku.value.specsText,
    is_checked: 1,
    is_effective: 1,
  })

  ElNotification.success('添加购物车成功')
}
// --------------- 添加购物车功能结束 ---------------



// ---------------- 直接购买功能开始 ----------------
const hanleBuyNow = async () => {
  if (!currSku.value) {
    ElMessage.error('请选择商品规格选项')
    return false
  }

  if (num.value > goods.value.amount) {
    ElMessage.error('库存不足')
    return false
  }

  // 组装生成订单参数
  let createOrderParams = {
    goods_id: goods.value.id,
    cover_url: currSku.value.cover_url ? currSku.value.cover_url : goods.value.cover_url,
    name: goods.value.name,
    goods_sku_id: currSku.value.skuId,
    goods_sepc_option_text: currSku.value.specsText,
    price: currSku.value.price,
    inventory_num: currSku.value.inventory_num,
    num: num.value,
  }

  orderStore.setCreateOrderParams(createOrderParams)
  router.push({path: '/confirm-order', query: {mode: 1}})
}
// ---------------- 直接购买功能结束 ----------------
</script>

<style scoped lang="scss">
.goods-detail-container {
  margin-bottom: 20px;
  padding-top: 140px;
  // 面包屑导航区域
  .crumbs-nav-wrap {
      font-size: 18px;
      padding: 20px 0;
      span {
        padding: 0 10px;
        &:first-child {
          padding-left: 0;
        }
        &:last-child {
          padding-right: 0;
        }
        a {
          &:hover {
            color: $main-color;
          }
        }
      }
  }

  .goods-wrap {
    min-height: 600px;
    background: #fff;
    display: flex;
    .image-wrap {
      width: 580px;
      height: 600px;
      padding: 30px 50px;
    }
    .info-wrap {
      flex: 1;
      padding: 30px 30px 30px 0;
      .btn-wrap {
        display: flex;
        height: 48px;
        line-height: 48px;
        margin-top: 20px;
        text-align: center;
        color: #fff;
        cursor: pointer;
        .add-cart-btn {
          width: 150px;
          background-color: #FF9E19;
          border-top-left-radius: 24px;
          border-bottom-left-radius: 24px;
        }
        .buy-btn {
          width: 150px;
          background-color: #F5312B;
          border-top-right-radius: 24px;
          border-bottom-right-radius: 24px;
        }
      }
    }
  }

  .goods-footer {
    display: flex;
    margin-top: 20px;
    .goods-article {
      width: 940px;
      margin-right: 20px;
    }
    .goods-aside {
      width: 280px;
      min-height: 1000px;
    }
  }
}
</style>